<template>
  <el-dialog :title="isEdit ? '修改用户信息': '新增用户信息'" :visible.sync="visible" :close-on-click-modal="closeOnClickModal" @open="_handleDialogOpen" @close="_cancel">
    <el-form ref="dataForm" :model="form" :status-icon="true" :rules="formRules" label-width="100px">
      <el-form-item label="登录账号" prop="username">
        <el-input
          v-model.trim="form.username"
          :placeholder="`请输入登录账号`"
          maxlength="11"/>
      </el-form-item>
      <el-form-item label="用户名称" prop="realname">
        <el-input v-model.trim="form.realname" :placeholder="`请输入用户名称`" maxlength="20" />
      </el-form-item>
      <el-form-item label="邮箱地址" prop="email">
        <el-input v-model="form.email" :placeholder="`请输入邮箱地址`" maxlength="180" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model.trim="form.phone"
          :placeholder="`请输入手机号`"
          type="p"
          maxlength="11"/>
      </el-form-item>
      <el-form-item v-if="!isEdit" label="密码">
        <el-tooltip
          :content="`默认密码为：123456`"
          effect="light"
          placement="top-start">
          <el-input v-model.trim="form.password" type="password" disabled />
        </el-tooltip>
      </el-form-item>
      <el-form-item label="账号状态">
        <el-switch v-model="form.enable" :active-value="1" :inactive-value="0" />
        <span :class="form.enable ? 'active': ''" class="switch-text">（{{ form.enable ? '启用' : '禁用' }}）</span>
      </el-form-item>
      <el-form-item label="是否为领导">
        <el-switch v-model="form.isLeader" :active-value="1" :inactive-value="0" @change="isLeader" />
        <span :class="form.isLeader ? 'active': ''" class="switch-text">（{{ form.isLeader ? '是' : '否' }}）</span>
      </el-form-item>
      <el-form-item v-if="form.isLeader" label="角色权限">
        <el-select v-model="form.leaderRole" placeholder="请选择" style="width:100%">
          <el-option
            v-for="item in leaderRoles"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.isLeader" label="所属单位">
        <el-select v-model="form.organs" placeholder="请选择" style="width:100%" @change="getFirstList">
          <el-option
            v-for="item in leaderOrgans"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.leaderRole == 2" label="管理单位">
        <el-select v-model="form.manageUnit" multiple placeholder="请选择" style="width:100%">
          <el-option
            v-for="item in manageUnits"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="备注信息">
        <el-input
          v-model="form.remark"
          :autosize="{minRows: 5, maxRows: 10}"
          :placeholder="`请输入备注信息`"
          type="textarea"
          maxlength="240"/>
      </el-form-item> -->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="_cancel">取 消</el-button>
      <el-button :loading="_loading" size="small" type="primary" @click="_ok">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getFirstList, getSecondList, getThirdList } from '@/api/systemManage/nodeType'
import organApi from '@/api/systemManage/organ'
import { getUserById } from '@/api/systemManage/user'
import waves from '@/directive/waves' // Waves directive
import defaultHeadImg from '@/assets/defaultHeadImg.png'
import { mapGetters } from 'vuex'

export default {
  directives: { waves },
  components: {
    // DetailCropper
  },

  props: {
    closeOnClickModal: {
      type: Boolean,
      default: false
    },

    loading: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      selectHeadImgInput: null,
      headImg: null,
      visible: false,
      isEdit: false,
      firstList: [],
      secondList: [],
      thirdList: [],
      leaderOrgans: [],
      selectOrgan: [],
      selectOrgan1: [],
      manageUnits: [],
      third: [],
      second: [],
      first: [],
      leaderOrgan: '',
      form: {},
      defaultPassword: this.$store.getters.defaultPassword,
      formRules: {
        username: [{
          required: true,
          message: '请填写登录账号'
        }, {
          validator: (rule, value, callback) => {
            if (value && !/^[a-z0-9_]+$/.test(value)) {
              callback(new Error(`登录账号只能包含英文字母、数字、下划线`))
            } else {
              callback()
            }
          },
          trigger: ['blur', 'change']
        }],
        realname: [{
          required: true,
          message: `请输入用户名称`
        }],
        email: [{
          type: 'email',
          message: `请输入正确的邮箱地址`,
          trigger: ['blur', 'change']
        }],
        phone: [{
          validator: (rule, value, callback) => {
            if (value && !/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(value)) {
              callback(new Error(`请输入正确的手机号`))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }]
      },
      leaderRoles: [{
        value: 1,
        label: '全部可看'
      }, {
        value: 2,
        label: '所管理单位可看'
      }, {
        value: 3,
        label: '仅分配可看'
      }]
    }
  },

  computed: {

    ...mapGetters([
      'lang'
    ]),

    validatePassword() {
      return this.form.password === this.defaultPassword
    },

    defaultHeadImg() { return defaultHeadImg },

    '_loading': {
      get() {
        return this.loading
      },

      set(value) {
        this.$emit('update:loading', value)
      }
    }
  },

  methods: {

    _formReset() {
      this.form = {
        username: '',
        type: '',
        nickName: '',
        sex: '',
        email: '',
        phone: '',
        password: this.defaultPassword,
        enable: 1,
        organs: '',
        // remark: '',
        leaderRole: '',
        manageUnit: [],
        realname: '',
        isLeader: 0
      }
      this.$nextTick(() => {
        this.$refs.dataForm.resetFields()
      })
    },

    _handleDialogOpen() {
      this._formReset()
      this.$emit('open')
    },

    _cancel() {
      this._formReset()
      this.visible = false
      this.isLoading = false
      this.$emit('cancel')
    },

    _ok() {
      const form = this.$refs['dataForm']
      form.validate(valid => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(this.form))
          this.$emit('ok', formData, this.isEdit)
        }
      })
    },

    show(params) {
      this.visible = true
      if (params) {
        this.isEdit = true
        getUserById(params.id || params).then(resp => {
          const data = resp.data
          this.form = data
        }).catch(resp => {
          this.$message.error(resp.message)
        })
      } else {
        this.isEdit = false
      }
    },

    isLeader(val) {
      organApi.getLeaderOrgan().then(resp => {
        this.leaderOrgans = resp.data
      }).catch(resp => {
        this.$message.error(resp.message)
      })
    },

    getFirstList(val) {
      console.log(val)
      this.leaderOrgan = val
      organApi.getManageUnits({ id: val }).then(resp => {
        this.manageUnits = resp.data
      })
      getFirstList({ id: val }).then(resp => {
        this.firstList = resp.data
      }).catch(resp => {
        this.$message.error(resp.message)
      })
    },

    getSecondList(val) {
      console.log(val)
      this.selectOrgan = val
      getSecondList({ selectIds: val, leaderOrgan: this.leaderOrgan }).then(resp => {
        this.secondList = resp.data
        this.thirdList = resp.data
      }).catch(resp => {
        this.$message.error(resp.message)
      })
    },

    getThirdList(val) {
      this.selectOrgan1 = []
      val.forEach(element => {
        this.selectOrgan1.push(element)
      })
      this.selectOrgan.forEach(element => {
        this.selectOrgan1.push(element)
      })
      this.selectOrgan.concat(val)
      console.log(this.selectOrgan)
      getThirdList({ selectIds: this.selectOrgan1, leaderOrgan: this.leaderOrgan }).then(resp => {
        this.thirdList = resp.data
      }).catch(resp => {
        this.$message.error(resp.message)
      })
    },

    close() {
      this._cancel()
    }
  }
}
</script>
